package com.cmcc.passenger.ui.order.adapter

import android.content.Context
import android.os.CountDownTimer
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.cmcc.passenger.R
import com.cmcc.passenger.data.entity.OrderRecordItem
import com.cmcc.passenger.databinding.ListItemMyOrderBinding
import com.cmcc.passenger.databinding.ListItemMyOrderTitleBinding
import com.cmcc.passenger.ui.order.viewmodel.MyOrderItemViewModel
import com.cmcc.shared.utils.TimeUtils
import java.text.SimpleDateFormat
import java.util.*

class OrderRecordAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private lateinit var context: Context
    private var currentList = mutableListOf<OrderRecordItem>()
    private var itemClickListener: MyOrderItemClickListener? = null
    private val countDownMap: SparseArray<CountDownTimer>? = SparseArray()

    override fun getItemCount(): Int {
        return currentList.size
    }

    fun addList(records: List<OrderRecordItem>) {
        currentList.addAll(records)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        this.context = parent.context
        if (viewType == R.layout.list_item_my_order) {
            return OrderRecordViewHolder(
                ListItemMyOrderBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        } else {
            return OrderRecordLabelHolder(
                ListItemMyOrderTitleBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val model = currentList[position]


        val currentType = getItemViewType(position)
        if (currentType == R.layout.list_item_my_order && holder is OrderRecordViewHolder) {
            holder.bind(context, model, createClickListener(model))
            holder.binding.orderStatus.alpha =
                holder.binding.viewModel?.statusAlpha?.get()?.toFloat() ?: 1.0.toFloat()
            var countDownTimer: CountDownTimer? =
                countDownMap?.get(holder.binding.orderStatus.hashCode())
            countDownTimer?.cancel()

            if (model.orderRecord.type == 2 && model.orderRecord.status == 0) {

                val isOrderInProgress = isOrderInProgress(
                    model.orderRecord.status ?: 0,
                    model.orderRecord.startTime ?: ""
                )

                if (isOrderInProgress) {
                    holder.binding.orderGap.text =
                        getOffTimeGap(context, model.orderRecord.startTime ?: "")

                    countDownTimer = object : CountDownTimer(30 * 60 * 1000L, 1000L) {
                        override fun onTick(millisUntilFinished: Long) {
                            holder.binding.orderGap.text =
                                getOffTimeGap(context, model.orderRecord.startTime ?: "")
                        }

                        override fun onFinish() {

                        }
                    }.start()
                } else {
                    holder.binding.orderGap.text =
                        TimeUtils.getOverTimeGap(context, model.orderRecord.startTime ?: "")

                    countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                        override fun onTick(millisUntilFinished: Long) {
                            holder.binding.orderGap.text =
                                TimeUtils.getOverTimeGap(context, model.orderRecord.startTime ?: "")
                        }

                        override fun onFinish() {

                        }
                    }.start()
                }

                countDownMap?.put(holder.binding.orderStatus.hashCode(), countDownTimer)
            } else {
                holder.binding.orderGap.text = ""
            }

        } else if (currentType == R.layout.list_item_my_order_title && holder is OrderRecordLabelHolder) {
            holder.binding.orderLabel.text =
                if (model.itemType == 1)
                    context.getString(R.string.passenger_order_current)
                else
                    context.getString(R.string.passenger_order_completed)
        }
    }

    private fun createClickListener(model: OrderRecordItem): View.OnClickListener {
        return View.OnClickListener { view ->
            itemClickListener?.click(view, model)
        }
    }

    fun addItemClickListener(listener: MyOrderItemClickListener) {
        itemClickListener = listener
    }

    override fun getItemViewType(position: Int): Int {
        return if (currentList[position].itemType == 0)
            R.layout.list_item_my_order
        else
            R.layout.list_item_my_order_title
    }

}

interface MyOrderItemClickListener {
    fun click(view: View, model: OrderRecordItem)
}

fun getOffTimeGap(context: Context, startTime: String): String {
    var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    var startDate: Date = format.parse(startTime)

    var nowTime: Date = Date()
    var timeGap = startDate.time - nowTime.time
    return if (timeGap > 0) {
        TimeUtils.getOffTimeGap(context, startTime)
    } else {
        context.getString(com.cmcc.shared.R.string.book_time_come)
    }
}

private fun isOrderInProgress(status: Int, startTime: String): Boolean {
    if (status == 0 && !startTime.isNullOrEmpty()) {
        var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        var startDate: Date = format.parse(startTime)

        var nowTime: Date = Date()
        var timeGap = startDate.time - nowTime.time
        if (timeGap > 0) {
            return false
        }
    }
    return true
}

class OrderRecordViewHolder(val binding: ListItemMyOrderBinding) :
    RecyclerView.ViewHolder(binding.root) {
    fun bind(context: Context, model: OrderRecordItem, listener: View.OnClickListener) {
        with(binding) {
            clickListener = listener
            viewModel =
                MyOrderItemViewModel(context, model)
        }
    }
}

class OrderRecordLabelHolder(val binding: ListItemMyOrderTitleBinding) :
    RecyclerView.ViewHolder(binding.root) {
    fun bind() {
        with(binding) {
            executePendingBindings()
        }
    }
}